<template>
  <div class="app-container">
    <el-form ref="training" :model="training" :rules="rules" label-width="120px">
      <div style="width: 450px">
        <el-form-item label="靶场名称" prop="trainingName" >
          <el-input v-model="training.trainingName" clearable/>
        </el-form-item>

      </div>
      <el-form-item label="靶场难度" prop="difficulty" clearable>
        <el-select v-model="training.difficulty" clearable placeholder="请选择">
          <el-option :value="0" label="低"/>
          <el-option :value="1" label="中"/>
          <el-option :value="2" label="高"/>
        </el-select>
      </el-form-item>

      <el-form-item label="靶场价格" prop="price" clearable>
        <el-input v-model="training.price" clearable />
      </el-form-item>

      <el-form-item label="是否vip" prop="isVip" >
        <el-select v-model="training.isVip" clearable placeholder="请选择">
          <el-option :value="0" label="非VIP靶场"/>
          <el-option :value="1" label="VIP靶场"/>
        </el-select>
      </el-form-item>

      <!-- 靶场图片：TODO -->
      <el-form-item label="靶场图片">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          class="avatar-uploader"
          action="http://localhost:8080/upload/">
          <img v-if="training.avatar" :src="training.avatar" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="addOrUpdate">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import training from '../../api/training'

export default {
  data() {
    const validateName = (rule, value, callback) => {
      // 区分是新增操作还是修改操作,根据有没有id来区分
      // 修改，要区分用户填写的名字是不是跟原本的名字一样的
      if (this.training.id) {
        if (this.oldName !== value) {
          training.nameOnly(value).then(res => {
            if (res.data === true) {
              callback()
            } else {
              callback(new Error('该名称已经被使用'))
            }
          })
        }
        callback()
      } else {
        // 新增
        // 给后端发起一个请求，查询该用户名是否存在
        training.nameOnly(value).then(res => {
          if (res.data === true) {
            callback()
          } else {
            callback(new Error('该名称已经被使用'))
          }
        })
      }
    }
    return {
      training: {
        avatar: ''
      },
      saveBtnDisabled: false,
      oldName: null,
      rules: {
        trainingName: [
          { required: true, message: '请输入靶场标题', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择靶场难度', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' }
        ],
        isVip: [
          { required: true, message: '请选择是否VIP靶场', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    if (this.$route.params && this.$route.params.id) {
      const id = this.$route.params.id
      this.selectTrainingById(id)
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.training.avatar = res.data
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'||
        file.type === 'image/png' ||
        file.type === 'image/jpg'
      const isLt2M = file.size / 1024 / 1024 < 20

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 20MB!')
      }
      return isJPG && isLt2M
    },
    addOrUpdate() {
      this.$refs['training'].validate((valid) => {
        if (valid) {
          if (this.training.id != null && this.training.id.length > 0) {
            this.updateTraining()
          } else {
            this.addTraining()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    addTraining() {
      training.add(this.training).then(res => {
        this.$message.success(res.message)
        this.$router.push({ path: '/training/list' })
      })
    },
    updateTraining() {
      training.add(this.training).then(res => {
        this.$message.success(res.message)
        this.$router.push({ path: '/training/list' })
      })
    },
    selectTrainingById(id) {
      training.selectTrainingById(id).then(res => {
        this.training = res.data[0]
        this.oldName = this.training.trainingName
      })
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
